package br.com.iswe.core.security.acegisecurity;

import java.util.Iterator;

import org.springframework.security.AccessDeniedException;
import org.springframework.security.Authentication;
import org.springframework.security.ConfigAttributeDefinition;
import org.springframework.security.vote.AbstractAccessDecisionManager;
import org.springframework.security.vote.AccessDecisionVoter;

public class AffirmativeBasedImpl extends AbstractAccessDecisionManager {

    //~ Methods ================================================================

    /**
     * This concrete implementation simply polls all configured  {@link
     * AccessDecisionVoter}s and grants access if any
     * <code>AccessDecisionVoter</code> voted affirmatively. Denies access
     * only if there was a deny vote AND no affirmative votes.
     * 
     * <p>
     * If every <code>AccessDecisionVoter</code> abstained from voting, the
     * decision will be based on the {@link #isAllowIfAllAbstainDecisions()}
     * property (defaults to false).
     * </p>
     *
     * @param authentication the caller invoking the method
     * @param object the secured object
     * @param config the configuration attributes associated with the method
     *        being invoked
     *
     * @throws AccessDeniedException if access is denied
     */
    @SuppressWarnings("unchecked")
	public void decide(Authentication authentication, Object object,
        ConfigAttributeDefinition config) throws AccessDeniedException {
        Iterator iter = this.getDecisionVoters().iterator();
        int deny = 0;

        while (iter.hasNext()) {
            AccessDecisionVoter voter = (AccessDecisionVoter) iter.next();
            int result = voter.vote(authentication, object, config);

            switch (result) {
            case AccessDecisionVoter.ACCESS_GRANTED:
                return;

            case AccessDecisionVoter.ACCESS_DENIED:
                deny++;

                break;

            default:
                break;
            }
        }

        if (deny > 0) {
            throw new AccessDeniedException("Access is denied: " + object.toString() + " ROLES: " + config.toString());
        }

        // To get this far, every AccessDecisionVoter abstained
        if (this.isAllowIfAllAbstainDecisions()) {
            return;
        } else {
            throw new AccessDeniedException("Access is denied" + object.toString() + " ROLES: " + config.toString());
        }
    }
}
